package org.atfeihu.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.atfeihu.springcloud.myhandler.CustomerBlockHandler;
import org.atfeihu.springcloud.service.LianLuService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author wangfeihu
 * @create 2021/9/10 19:10
 */
@RestController
@Slf4j
public class FlowLimitController {

    @Resource
    private LianLuService lianLuService;

    @GetMapping("/testA")
    @SentinelResource(value = "testA", blockHandler = "testAHandler")
    public String testA() {
        return "============> testA";
    }
    public static String testAHandler(BlockException e) {
        return "我是A, 您访问太快被限流了！！！!";
    }

    @GetMapping("/testB")
    @SentinelResource(value = "testB", blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handlerB")
    public String testB() {
        try { TimeUnit.SECONDS.sleep(1); }catch (Exception e) {e.printStackTrace();}
        log.info("============> currentTime: " + LocalDateTime.now());
        return "============> testB";
    }

    @GetMapping("/testC")
    public String testC() {
        return lianLuService.lianlu() + "============> testC";
    }

    @GetMapping("/testD")
    public String testD() {
        return lianLuService.lianlu() + "============> testD";
    }

    @GetMapping("/hotKey")
    @SentinelResource(value = "hotKey", blockHandler = "hotKeyHandler")
    public String testHotKey(
            @RequestParam(value = "a", required = false) String a,
            @RequestParam(value = "b", required = false) String b) {
        return "hotKey";
    }
    public static String hotKeyHandler(@RequestParam(value = "a", required = false) String a,
                                       @RequestParam(value = "b", required = false) String b, BlockException e) {
        return "hostKey request faster";
    }


    @GetMapping("/retaLimit/byUrl")
    public String retaLimit() {
        return "/retaLimit/byUrl successful!";
    }
}
